package com.alliky.core.net.interceptors;

import com.google.gson.Gson;

import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okhttp3.internal.platform.Platform;
import okio.Buffer;
import okio.BufferedSource;

import static okhttp3.internal.platform.Platform.INFO;

/**
 * @Author: wxianing
 * @CreateDate: 2022/3/5 21:28
 * @Description: java类作用描述
 */
public class LoggingInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");
    private Gson mGson = new Gson();

    public enum Level {
        NONE,//不打印
        BODY,//打印头部 url 参数 返回值
    }

    public interface Logger {
        void log(String message);

        /**
         * A {@link LoggingInterceptor.Logger} defaults output appropriate for the current platform.
         */
        LoggingInterceptor.Logger DEFAULT = new LoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Platform.get().log(message, INFO, null);
            }
        };
    }

    public LoggingInterceptor() {
        this(LoggingInterceptor.Logger.DEFAULT);
    }

    public LoggingInterceptor(LoggingInterceptor.Logger logger) {
        this.logger = logger;
    }

    private final LoggingInterceptor.Logger logger;

    private volatile LoggingInterceptor.Level level = LoggingInterceptor.Level.NONE;

    /**
     * Change the level at which this interceptor logs.
     */
    public LoggingInterceptor setLevel(LoggingInterceptor.Level level) {
        if (level == null) throw new NullPointerException("level == null. Use Level.NONE instead.");
        this.level = level;
        return this;
    }

    public LoggingInterceptor.Level getLevel() {
        return level;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        LoggingInterceptor.Level level = this.level;

        Request request = chain.request();
        if (level == Level.NONE) {
            return chain.proceed(request);
        }

        String method = request.method();

        boolean logBody = level == Level.BODY;

        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;

        HashMap headerParam = new HashMap();
        String params = "";
        Headers headers = request.headers();

        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                headerParam.put(name, headers.value(i));
            }
        }

        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyHasUnknownEncoding(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            if (isPlaintext(buffer)) {
                params = buffer.readString(charset);
//                logger.log(buffer.readString(charset));
            } else {
                logger.log("--> END " + request.method() + " (binary "
                        + requestBody.contentLength() + "-byte body omitted)");
            }
        }

        Response response;

        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            logger.log("<-- HTTP FAILED: " + e);
            throw e;
        }

        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        String responseData = "";

        if (!logBody || !HttpHeaders.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyHasUnknownEncoding(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            if (!isPlaintext(buffer)) {
                logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }

            if (contentLength != 0) {
                responseData = buffer.clone().readString(charset);
            }
        }

        if (logBody) {
            logger.log(" " + response.code()
                    + " " + method + " "
                    + "url: " + response.request().url() + "\n"
                    + " headers: " + mGson.toJson(headerParam) + "\n"
                    + " params: " + params + "\n"
                    + " " + responseData
            );
        }

        return response;
    }

    static boolean isPlaintext(Buffer buffer) {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            return false; // Truncated UTF-8 sequence.
        }
    }

    private boolean bodyHasUnknownEncoding(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null
                && !contentEncoding.equalsIgnoreCase("identity")
                && !contentEncoding.equalsIgnoreCase("gzip");
    }
}
